package sunwin.yoms.dao.comm;

import sunwin.yoms.comm.YomsException;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class JDBCHelper {

    private final static String connectionString = "jdbc:log4jdbc:mysql://%s:%s/%s?&user=%s&password=%s&characterEncoding=utf8&autoReconnectForPools=true";

    private JDBCHelper() {

    }

    static {
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }



    private static Connection getConnection(String connectionString) throws SQLException {
        Connection connection = DriverManager.getConnection(connectionString);
        return connection;
    }

    private static void close(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<Map<String, Object>> convert(ResultSet rs) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        if (rs != null && !rs.isClosed()) {
            ResultSetMetaData meta = rs.getMetaData();
            int colCount = meta.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= colCount; i++) {
                    String key = meta.getColumnName(i);
                    Object value = rs.getObject(i);
                    map.put(key, value);
                }
                list.add(map);

            }
        }
        return list;
    }

    private static void AttachParameters(PreparedStatement statement, Object... values) throws Exception {
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                statement.setObject(i + 1, values[i]);
            }
        }
    }

    /**
     * 获取第一行第一列的int数据
     * @param sql
     * @param connectionString
     * @param parameterValues
     * @return
     * @throws SQLException
     * @throws Exception
     */
    public static int ExecuteNonQuery(String sql, String connectionString, Object... parameterValues) throws SQLException, Exception {
        Connection connection = null;
        PreparedStatement statement = null;
        int result = 0;
        try {
            connection = getConnection(connectionString);
            statement = connection.prepareStatement(sql);
            AttachParameters(statement, parameterValues);
            result = statement.executeUpdate();
            statement.clearParameters();
        } finally {
            close(statement);
            close(connection);
        }
        return result;
    }

    /**
     * 获取详细数据列表
     * map string 列名
     * map object 列值
     * map 行数据
     * list 行数据集合
     * @param sql
     * @param connectionString
     * @param parameterValues
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> ExecuteList(String sql, String connectionString, Object... parameterValues) throws Exception {
        PreparedStatement statement = null;
        Connection connection = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            connection = getConnection(connectionString);
            rs = ExecuteResultSet(sql, connection, statement, parameterValues);
            list = convert(rs);
        } finally {
            close(statement);
            close(rs);
            close(connection);
        }
        return list;
    }

    /**
     * 获取第一行第一列的object数据
     * @param sql
     * @param connectionString
     * @param parameterValues
     * @return
     * @throws Exception
     */
    public static Object ExecuteScalar(String sql, String connectionString, Object... parameterValues) throws Exception {
        PreparedStatement statement = null;
        Connection connection = null;
        ResultSet rs = null;
        Object value = null;
        try {
            connection = getConnection(connectionString);
            rs = ExecuteResultSet(sql, connection, statement, parameterValues);
            if (rs != null) {
                rs.next();
                value = rs.getObject(1);
            }
        } finally {
            close(statement);
            close(rs);
            close(connection);
        }

        return value;
    }

    /**
     * 基础查询函数，当调用此函数时需手动关闭resultSet对象和connection对象
     * 连接数据库
     * 注入参数
     * 执行sql语句
     * 清除参数
     * @param sql
     * @param connection
     * @param statement 该参数处于测试阶段，如果内部可以关闭掉参数注入则将会取消该参数
     * @param parameterValues
     * @return
     * @throws Exception
     */
    public static ResultSet ExecuteResultSet(String sql, Connection connection, PreparedStatement statement, Object... parameterValues) throws Exception {
        ResultSet rs = null;
        try {
            statement = connection.prepareStatement(sql);
            AttachParameters(statement, parameterValues);
            rs = statement.executeQuery();
            statement.clearParameters();
        } catch (Exception e) {
            close(rs);
            close(connection);
            throw e;
        }
        return rs;
    }

    /**
     * 获取数据库所有表名
     *
     * @return
     * @throws YomsException
     */
    public static List<String> getTableNames(String connectionString, String dataBase) throws YomsException {
        PreparedStatement statement = null;
        Connection connection = null;
        List<String> tables = new ArrayList<>();
        String sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = ?";
        ResultSet set = null;
        try {
            connection = getConnection(connectionString);
            set = JDBCHelper.ExecuteResultSet(sql, connection, statement, dataBase);
            while (set.next()) {
                tables.add(set.getObject("table_name") + "");
            }
        } catch (Exception e) {
            throw YomsException.getInstance("获取数据库所有表名出现异常");
        } finally {
            close(statement);
            close(set);
            close(connection);
        }
        return tables;
    }

    /**
     * 表是否存在
     *
     * @return
     */
    public static boolean tableIsExist(String connectionString, String dataBase, String tableName) throws YomsException {
        String sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_name = ?";
        try {
            Object obj = JDBCHelper.ExecuteScalar(sql, connectionString, dataBase, tableName);
            return obj != null;
        } catch (Exception e) {
            throw YomsException.getInstance("判断表名是否存在出现异常");
        }
    }

    public static String getConnString(String address, String port, String database, String user, String password) throws YomsException {
        return String.format(connectionString, address, port, database, user, password);
    }
}